//
//  LGFAddressPickerView.swift
//  Auscultation
//
//  Created by 来 on 2020/12/24.
//

import Foundation

protocol LGFAddressPickerViewDelegate: class {
    func selectIndex(view: LGFAddressPickerView!, name: String, address: String)
}

class LGFAddressPickerView: UIView {

    weak var delegate: LGFAddressPickerViewDelegate?
    
    var bgView: UIView!
    
    var label: UILabel!
    
    var provinceArr: [Any] = []
    var cityArr: [[String: Any]] = []
    var areaArr: [String] = []
    
    var picker: UIPickerView!
    
    var selectIndex1: Int = 0
    var selectIndex2: Int = 0
    var selectIndex3: Int = 0
    
    var callBack: ((LGFAddressPickerView?, String, String) -> Void)!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func showIn(_ SV: UIView, _ callBack: @escaping (LGFAddressPickerView?, String, String) -> Void) -> Void {
        self.callBack = callBack
        SV.addSubview(self)
        lgf_FillSuperview()
         
        self.provinceArr = NSArray.init(contentsOfFile: Bundle.main.path(forResource: "area.plist", ofType: nil)!) as? [Any] ?? []
        
        config()
        
        bgView.transform = CGAffineTransform.init(translationX: 0, y: UIDevice.lgf_ScreenH / 2)
        DispatchQueue.main.async {
            UIView.animate(withDuration: 0.35) {
                self.bgView.transform = CGAffineTransform.identity
                self.backgroundColor = UIColor.black.withAlphaComponent(0.2)
            }
        }
    }
    
    func config() -> Void {
        bgView = UIView.init()
        bgView.backgroundColor = UIColor.white
        addSubview(bgView)
        bgView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(UIDevice.lgf_ScreenH / 2.5)
        }
        
        let topView = UIView.init()
        bgView.addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(50.lgf_H())
        }
        
        let leftButton = UIButton.init(type: .custom)
        leftButton.setTitle("取消", for: .normal)
        leftButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 16)
        leftButton.setTitleColor(UIColor.init(lgf_HexString: "0F88F2"), for: .normal)
        leftButton.addTarget(self, action: #selector(leftButtonSelect(_:)), for: .touchUpInside)
        topView.addSubview(leftButton)
        leftButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15.lgf_W())
            make.centerY.equalToSuperview()
        }
        
        let rightButton = UIButton.init(type: .custom)
        rightButton.setTitle("确认", for: .normal)
        rightButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 16)
        rightButton.setTitleColor(UIColor.init(lgf_HexString: "0F88F2"), for: .normal)
        rightButton.addTarget(self, action: #selector(rightButtonSelect(_:)), for: .touchUpInside)
        topView.addSubview(rightButton)
        rightButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15.lgf_W())
            make.centerY.equalToSuperview()
        }
        
        label = UILabel.init()
        label.textColor = UIColor.init(lgf_HexString: "111111")
        label.font = UIFont.systemFont(ofSize: 16)
        label.textAlignment = .center
        label.text = lgf_ViewName
        topView.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.6)
        }
        
        picker = UIPickerView.init()
        picker.delegate = self
        picker.dataSource = self
        bgView.addSubview(picker)
        picker.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(topView.snp.bottom)
        }
    }
    
    @objc func leftButtonSelect(_ sender: UIButton) -> Void {
        remove()
    }
    
    @objc func rightButtonSelect(_ sender: UIButton) -> Void {
        let province = provinceArr.count > 0 ? ((provinceArr[self.selectIndex1] as? [String: Any])?["state"] as? String) ?? "" : ""
        let city = cityArr.count > 0 ? (cityArr[self.selectIndex2]["city"] as? String) ?? "" : ""
        let area = areaArr.count > 0 ? (areaArr[self.selectIndex3]) : ""
        let address = [province, city, area].filter({ (ad) -> Bool in
            return ad != ""
        }).joined(separator: ",")
        self.delegate?.selectIndex(view: self, name:self.lgf_ViewName ?? "", address: address)
        self.callBack(self, self.lgf_ViewName ?? "", address)
        remove()
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if touches.first?.view == self {
            remove()
        }
    }
    
    func remove() -> Void {
        UIView.animate(withDuration: 0.35, animations: {
            self.bgView.transform = CGAffineTransform.init(translationX: 0, y: UIDevice.lgf_ScreenH / 2)
            self.backgroundColor = UIColor.black.withAlphaComponent(0.0)
        }) { (finish) in
            self.removeFromSuperview()
        }
    }

}

extension LGFAddressPickerView: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 3
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return provinceArr.count
        } else if component == 1 {
            return cityArr.count
        } else {
            return areaArr.count
        }
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            return (provinceArr[row] as? [String: Any])?["state"] as? String
        } else if component == 1 {
            return cityArr[row]["city"] as? String
        } else {
            return areaArr[row]
        }
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
            self.cityArr = (provinceArr[row] as? [String: Any])?["cities"] as? [[String: Any]] ?? []
            pickerView.selectRow(0, inComponent: 1, animated: false)
            pickerView.reloadComponent(1)
            if self.cityArr.count != 0 {
                areaArr = cityArr[0]["areas"] as? [String] ?? []
                pickerView.selectRow(0, inComponent: 2, animated: false)
                pickerView.reloadComponent(2)
            }
            self.selectIndex1 = row
        } else if component == 1 {
            if cityArr.count == 0 {
                return
            }
            areaArr = cityArr[row]["areas"] as? [String] ?? []
            pickerView.selectRow(0, inComponent: 2, animated: false)
            pickerView.reloadComponent(2)
            self.selectIndex2 = row
        } else {
            if areaArr.count == 0 {
                return
            }
            self.selectIndex3 = row
        }
    }
}
